/*****目标团队--靶标 --渗透*****/
<template><!---->
	<search-table
	    ref="searchTable"
		:columns="targetTeamCol"
        :data="targetAllotList"
		:total="targetAllotTotal"
		:page.sync="queryTargetAllotInfo.pageIndex"
		:size.sync="queryTargetAllotInfo.pageSize"
		@change-size="getTargetSize"
		@change-page="getTargetPage"
		:disabled="disabledAllBtn"
		showSelectTag
		:selection.sync="selectTargetAllots"
	>
    <template slot="search">
		<!-- <Checkbox
				v-if="type == 7"
				v-model="selectAll"
				:disabled="disabledAllBtn"
				style="margin-right:15px;">全选</Checkbox> -->
		<Button  type='primary' ghost @click="showAddAndUpdate('')" :disabled="disabledAllBtn" v-if="type == 7" style="margin-right:15px;"><img src="../../../../assets/scene/auto-target-allot-purple.png" alt="" />任务分配</Button>
		<Poptip
				v-if="isRandom"
				confirm
				title="确认展示选中的任务吗?"
				@on-ok="batchModificationStatus(1)"
				transfer>
			<Button type='primary'
					ghost
					:disabled="disabledAllBtn"
					v-if="type == 7"
					style="margin-right:15px;">批量展示</Button>
		</Poptip>
		<Poptip
				v-if="isRandom"
				confirm
				title="确认隐藏选中的任务吗?"
				@on-ok="batchModificationStatus(0)"
				transfer>
			<Button type='primary'
					ghost
					:disabled="disabledAllBtn"
					v-if="type == 7"
					style="margin-right:15px;">批量隐藏</Button>
		</Poptip>
		<Button  type='primary' ghost @click="autoAllotTopoTarget()" :disabled="disabledAllBtn || targetTeamTotal == 0" v-if="type == 4" style="margin-right:15px;"><img src="../../../../assets/scene/auto-target-allot-purple.png"  alt="" />一键配置</Button>
		<Select filterable v-model="queryTargetAllotInfo.teamName"
				style="width: 150px; margin-right:15px;"
				@on-change="getTargetPage(1)" clearable
				placeholder="请选择团队">
			<Option v-for="item in accessGroupList" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
		</Select>
		<Select filterable v-model="queryTargetAllotInfo.targetName" placeholder="请选择任务" @on-change="getTargetPage(1)"
				style="width:150px; margin-right:15px;" transfer clearable>
			<Option v-for="item in targetTeamData" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
		</Select>
			<Select filterable v-model="queryTargetAllotInfo.visibility" placeholder="是否显示" @on-change="getTargetPage(1)" clearable style="width:150px;margin-right:15px;">
			<Option  :value="1">是</Option>
			<Option  :value="0">否</Option>
		</Select>
		<!--<DatePicker format="yyyy-MM-dd HH:mm:ss" type="daterange"  placeholder="选择日期" style="width: 200px"
					@on-change="searchTargetPrjD"></DatePicker>-->
		<!--<Input v-model.trim="searchPrjString" search placeholder="任务显示名称" style="width: 200px" @on-search="searchTargetPrj"  />-->
	</template>
  <Modal v-model="targetModal.show"
			  :title="targetModal.title"
			  :loading = "targetModal.loading"
			  width="800px"
			  :mask-closable = "false"
			  @on-cancel="closeTargetModal"
			  @on-ok="targetAllot">
			<Alert type="warning" show-icon>
				<p>已完成任务或提交过报告的团队不允许撤销分配</p>
			</Alert>
			<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
			  <FormItem label="任务" prop="targetId">
				<Select filterable v-model="formValidate.targetId" placeholder="请选择任务" @on-change="changeTarget" filterable>
				  <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id" :title="target.name">{{target.name}}</Option>
				</Select>
			  </FormItem>
			  <FormItem label="团队" prop="teamIds">
				<Select filterable  v-model="formValidate.teamIds" placeholder="请选择团队" @on-change="changeTeamGroup" multiple class="not-close">
				  <Option v-for="item in accessGroupList" :value="item.id" :key="item.id" :title="item.name" :disabled="item.disabled">{{item.name}}</Option>
				</Select>
			  </FormItem>
			  <FormItem  label="是否显示" prop="visibility" v-if="stMode == 1">
				<RadioGroup v-model="formValidate.visibility">
				  <Radio :label=1>显示</Radio>
				  <Radio :label=0>不显示</Radio>
				</RadioGroup>
				<span style="color:#f90"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
			  </FormItem>
			 </Form>
		  </Modal>
		  <Modal v-model="modifyTargetModal.show"
			  :title="modifyTargetModal.title"
			  :loading = "modifyTargetModal.loading"
			  width="600px"
			  :mask-closable = "false"
			  @on-cancel="handleReset('allotFormValidate')"
			  @on-ok="modifyTargetAllot">
			<Form ref="allotFormValidate" :model="allotFormValidate" :rules="ruleValidate" :label-width="100">
			  <FormItem label="任务" prop="basicTargetId">
				<Select filterable v-model="allotFormValidate.basicTargetId" placeholder="请选择任务" @on-change="changeTarget" filterable>
				  <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id" :title="target.name">{{target.name}}</Option>
				</Select>
			  </FormItem>
			  <FormItem label="团队" prop="teamId">
				<Select filterable  v-model="allotFormValidate.teamId" placeholder="请选择团队" filterable>
				  <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
				</Select>
			  </FormItem>
			  <!--<FormItem label="虚拟机" prop="vmId" v-if="modifyTargetModal.show" disabled>
				<Select filterable v-model="allotFormValidate.vmId" placeholder="请选择虚拟机" filterable>
				  <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
				</Select>
			  </FormItem>-->
			  <FormItem  label="是否显示" prop="visibility">
				<RadioGroup v-model="allotFormValidate.visibility">
				  <Radio :label=1>显示</Radio>
				  <Radio :label=0>不显示</Radio>
				</RadioGroup>
				<!--<span style="color:#f90"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>-->
			  </FormItem>
			  <!--<FormItem  label="服务内网端口" prop="externalServicePort" v-if="type == 1">
				<Input v-model.trim="allotFormValidate.externalServicePort" placeholder="请输入PORT(1~65535)"></Input>
			  </FormItem>
			  <FormItem  label="外网IP" prop="externalIp">
				<Input v-model.trim="allotFormValidate.externalIp" placeholder="请输入对外IP"></Input>
			  </FormItem>-->
			  <!--<FormItem  label="外网端口" prop="externalPort">
				<Input v-model.trim="allotFormValidate.externalPort" placeholder="请输入PORT(1~65535)"></Input>
			  </FormItem>-->
			</Form>
		  </Modal>
		  </search-table>
</template>

<script>
  import
  {getTargetTeamList_new,queryVmWithParty,queryNetworkList,targetAllot,queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot,autoAllotTopoTarget,getPhyDevNodeList,getSceneInfo,batchModificationStatus, ctfReport} from '@/api/drill_compete'
  import {queryCtfList} from '@/api/question'
  import {getFlagServerList,getstatusbyprjid} from '@/api/drill'
  import {getaccessgrouplist} from '@/api/access_new'
	export default {
    name: 'scenes',
    props:['type','disabledAllBtn','step'],
    components:{},
	data(){
		const validateNum = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('请输入1-100的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
	  	return {
			currentTargetId: '',
            selectAll: false,
		    isMultiple: true,
			routeParams:{
	          id:this.$route.query.id,
	          prjid:this.$route.query.prjid
	        },
	        targetModal:{
	        	show:false,
	        	title:'',
	        	loading:true,
	        	type:1 //1添加，2修改
	        },
	        modifyTargetModal:{
	        	show:false,
	        	title:'修改分配',
	        	loading:true
	        },
	        pathList:[],
			accessGroupList:[],
	        vmlists:[],
	        allVms:[],
	        teamlists:[],
			queryTargetTeamInfo:{
				pageIndex:1,
				pageSize:2147483647,
				sceneId:this.$route.query.id,
				projectId:this.$route.query.prjid
			},
			queryTargetAllotInfo:{
				pageIndex:1,
				pageSize:10,
				sceneId:this.$route.query.id
			},
	        questionList:[],
	        access:'1',
	        formValidate: {
			  "idsTOS": [],
			  "targetId": "",
			  "teamIds": [],
			  "visibility": 0,
	        },
	        allotFormValidate:{
			  "createTime": "",
			  "externalIp": "",
			  "externalPort": "",
			  "externalServicePort": "",
			  "id": "",
			  "sceneId": "",
			  "subnetId": "",
			  "subnetName": "",
			  "targetId": "",
			  "targetName": "",
			  "teamId": "",
			  "teamName": "",
			  "visibility": 0,
			  "vmId": "",
			  "vmName": ""
	        },
	        oldFormValidate:{},
	        ruleValidate: {
//			  subnetId:[
//	          	{ required: true, message: '请选择子网络', trigger: 'change'}
//	          ],
//	          questionId:[
//	          	{ required: true, message: '请选择任务', trigger: 'change'}
//	          ],
	          visibility:[
	          	{ required: true, type:'number',message: '请选择', trigger: 'change'}
	          ],
//	          vmId:[
//	          	{ required: true, message: '请选择虚拟机', trigger: 'change'}
//	          ],
	          teamIds:[
	          	{ required: true, type:'array',min:1,message: '请选择团队', trigger: 'change'}
	          ],
	          targetId:[
	          	{ required: true, message: '请选择靶标', trigger: 'change'}
	          ],
	          basicTargetId:[
	          	{ required: true, message: '请选择靶标', trigger: 'change'}
	          ],
	          idsTOS:[
	          	{ required: true,type:'array',min:1, message: '请添加人员设备', trigger: 'change'}
	          ]
	        },
	        querytime:{},
	        targetTeamCol:[
	//        {
	//          type: 'index',
	//          align: 'center',
	//          ellipsis:true,
	////          width:60
	//        },
				{
					type:'selection',
					width:60,
					show:this.isRandom
				},
	          {
	            title:'任务显示名称',
	            key:'targetName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-left',
                  width: 240
	//          width:100
	          },
//		      {
//	        	title:'子网络名称',
//	            key:'subnetName',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	            width:100
//		      },
		      {
	            title:'团队名称',
	            key:'teamName',
	            align:'center',
	            tooltip:true,
	            width:100
//	            render:(h, params) => {
//	              return h('span',this.typeFilter(params.row.type))
//	            }
	          },
	          {
	            title:'虚拟机名称',
	            key:'vmName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:100
	          },
//	          {
//	            title:'团队名称',
//	            key:'teamName',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	            width:100
//	          },

	//        {
	//          title:'验证码类型',
	//          key:'targetsubmittype',
	//          align:'center',
	//          width:140,
	//          render:(h, params) => {
	//            return h('span',this.targetSubmitTypeFilter(params.row.targetsubmittype))
	//          }
	//        },
	//        {
	//          title:'虚拟机名称',
	//          key:'vmname',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
			  {
	            title:'内网IP',
	            key:'ip',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:100
	          },
	          {
	            title:'内网服务端口',
	            key:'servicePort',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:60
	          },
//	          {
//	            title:'服务内网端口',
//	            key:'externalServicePort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	            render:(h,params) => {
//	            	return h('span',params.row.targetTempInfos.filter(t => t.type == 3).length > 0 ? params.row.targetTempInfos.filter(t => t.type == 3)[0].info : '')
//	            }
//	          },
	          {
	            title:'路径',
	            key:'flagPath',
	            align:'center',
	            tooltip:true,
	            width:100
//	            render:(h,params) => {
//	            	return h('span',params.row.targetTempInfos.filter(t => t.type == 1).length > 0 ? params.row.targetTempInfos.filter(t => t.type == 1)[0].info : '')
//	            }
	          },
//	          {
//	            title:'外网IP',
//	            key:'externalIp',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
//	          {
//	            title:'外网访问端口',
//	            key:'externalPort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
	          {
	            title:'显示状态',
	            key:'visibility',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-right',
	            render:(h,params) => {
					return h('Tag',{
						props:{
						   color:params.row.visibility == 1 ? 'success' :'default',
						   type:"border"
						},
						style:{
							cursor: this.isRandom ? 'pointer!important' : 'default!important'
						},
						nativeOn:{
		                    click: this.isRandom ? ()=>{
                                this.handleConfirm(params)
		                    } : () => {}
		                }
					},params.row.visibility == 1 ? '是' : '否' )
				}
	          },
	          {
	            title:'分值',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:60
	          },
	          {
	            title:'描述',
	            key:'description',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:100
	          },
//	          {
//	            title:'操作',
//	            key:'os',
//	            ellipsis:true,
//	            width:100,
//	            action:true,
//	            placement:'top-right',
//	            render:(h,params)=>{
//	              return h('div',[
//		            h('Button',{
//	                  props:{
//	                    type:'text',
//	                    size:'small',
//	                    disabled:this.disabledAllBtn
//	                  },
//	                  attrs:{
//	                  	title:'修改'
//	                  },
//	                  style:{
//	                    border:'none',
//						background:'none',
//						boxShadow:'none'
//	                  },
//	                  on:{
//	                    click:()=>{
//	                      this.modifyTargetModal.show = true;
//	                      this.allotFormValidate = JSON.parse(JSON.stringify(params.row));
//	                      this.getAllVmlist();
//	                    }
//	                  }
//	                },[
//	                	h('img', {
//	                    attrs: {
//	                    	src:this.disabledAllBtn ? require('../../../../assets/project/modifys.png') : require('../../../../assets/project/modifys-h.png')
//	                    },
//	                    style: {
//	                        cursor: 'pointer',
//	                        'vertical-align': 'middle',
//	                        display:'inline-block',
//	                        marginBottom:'4px',
//	                    },
//	                  })
//	                ]),
//	                h('Poptip', {
//	                  props: {
//	                    confirm: true,
//	                    'ok-text': "确定",
//	                    'cancel-text': "取消",
//	                    type: 'error',
//	                    size: 'large',
//	                    title: '你确定要删除吗?',
//	                    transfer:true
//	                  },
//	                  on: {
//	                    'on-ok': () => {
//	                      this.delTargetTeam(params.row.id)
//	                    }
//	                  }
//	                }, [
//	                  h('Button', {
//	                    props: {
//	                      type: 'text',
//	                      size: 'small',
//	                      disabled:this.disabledAllBtn
//	                    },
//	                    attrs:{
//	                    	title:'删除'
//	                    },
//	                    style: {
//	                      border:'none',
//						  background:'none',
//						  boxShadow:'none'
//	                    },
//	                  },[
//	                  	h('img', {
//	                        attrs: {
//	                        	src:this.disabledAllBtn ? require('../../../../assets/project/delNote-d.png') : require('../../../../assets/project/delNote-h.png')
//	                        },
//	                        style: {
//	                            cursor: 'pointer',
//	                            'vertical-align': 'middle',
//	                            display:'inline-block',
//	                            marginBottom:'4px',
//	                        },
//	                    })
//	                  ])
//	                ])
//	              ])
//	            }
//	          }
	        ],
	        idsTOSCol:[
	          {
	            title:'团队',
	            key:'teamName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
//	          {
//	            title:'子网络',
//	            key:'subnetName',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
	          {
	            title:'虚拟机',
	            key:'vmName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
//	          {
//	            title:'外网IP',
//	            key:'externalIp',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
//	          {
//	            title:'外网端口',
//	            key:'externalPort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
	          {
	            title:'是否显示',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            render:(h,params) => {
					return h('Tag',{
						props:{
						   color:params.row.visibility == 1 ? 'success' :'default',
						   type:"border"
						},
						on:{
		                    click:()=>{
		                      //this.showAddAndUpdate(params.row)
		                    }
		                }
					},params.row.visibility == 1 ? '是' : '否' )
				}
	          },
	          {
	            title:'操作',
	            key:'os',
	            ellipsis:true,
//	            width:200,
	            render:(h,params)=>{
	              return h('div',[
	                h('Button',{
	                  props:{
	                    type:'primary',
	                    size:'small'
	                  },
	                  style:{
	                    marginRight:'5px'
	                  },
	                  on:{
	                    click:()=>{
	                        let index = this.formValidate.idsTOS.findIndex(item => item.id == params.row.id);
	                        this.formValidate.idsTOS.splice(index,1);
	                    }
	                  }
	                },'移除')
	              ])
	            }
	          }
	        ],
	        targetTeamData:[],
	        targetTeamTotal:0,
	        TargetId:'',
	        projectInfo:{},
	        subnetList:[],
	        networkId:'',
	        teamArr:[],
	        networkArr:[],
	        vmArr:[],
	        idwithName:{},
	        targetAllotList:[],
	        targetAllotTotal:0,
			selectTargetAllots:[],
			wpUpMode: 1, // 提交报告模式
            stMode: 0 // 答题类型：0排序；1随意
	  	}
	},
	filters:{

	},
	computed:{
        isRandom() {
            return this.stMode === 1
        }
	},
	mounted(){
    	this.getAccessGroupList();
    	this.getAllVmlist();
    	this.getPhyDevNodeList();
    	this.getTargetTeamList();
    	this.queryTargetAllot();
        getSceneInfo(this.$route.query.id).then(data => {
            if(data.code == 1){
                let { extension } = data.data
                extension = extension || '{}'
                this.stMode = JSON.parse(extension).stMode || 0;
                if(this.stMode == 0){
                    this.formValidate.visibility = 1
                }
				this.wpUpMode = JSON.parse(extension).wpUpMode || 1;
            }
        });
	},
    watch: {
        selectAll(newValue) {
            this.targetAllotList = this.targetAllotList.map(item => {
                item.checked = newValue
                return item
            })
        },
		currentTargetId(newVal) {
			if (!newVal) {
				this.accessGroupList.forEach(item => item.disabled = false)
			} else {
				Promise.all(this.accessGroupList.map(async item => {
					await this.getTargetCompleteness(item).then(res => {
						item.disabled = res
					})
					return item
				})).then(res => {
					this.accessGroupList = res
				})
			}
		}
    },
    methods:{
		// 查询靶标完成度，靶标不处于初始状态或者有相关的提交，都不允许再选择
		getTargetCompleteness(item) {
			return new Promise(resolve => {
				let template = this.targetTeamData.find(item => item.id === this.currentTargetId)
				if (!template) {
					return
				}
				let targetName = template.name
				Promise.all([queryTargetAllot({
					pageIndex: 1,
					pageSize: 1,
					teamId: item.id,
					sceneId: this.$route.query.id,
					targetName
				}), ctfReport(this.$route.query.id, item.id, {
					questionName: this.wpUpMode !== 1 ? targetName : undefined
				})]).then(([res1, res2]) => {
					if (res1.code === 1 && res2.code === 1) { // 均正确获取数据，不然不做处理
						resolve(!!(res1.data.items && res1.data.items[0] && res1.data.items[0].status !== 1) || !!(res2.data && res2.data.length))
					} else {
						resolve(false)
					}
				}).catch(() => {
					resolve(false)
				})
			})
		},
        handleConfirm(params) {
            const title = params.row.visibility === 1 ? '隐藏任务' : '展示任务'
            const content = params.row.visibility === 1 ? '确认隐藏任务吗？' : '确认展示任务吗？'

            this.$Modal.confirm({
                title,
                content,
                onOk: () => {
                    let visibility = 0;
                    if(params.row.visibility == 0){
                        visibility = 1;
                    }
                    modifyTargetAllot(params.row.id,{visibility:visibility}).then(data => {
                        if(data.code == 1){
                            this.queryTargetAllot();
                            this.$Message.info('操作成功');
                        }else{
                            this.$Message.warning(data.message);
                        }
                    }).catch(() => {
                    })
                }
            });
        },
        // 批量操作
        batchModificationStatus(status) {
            let checklist = this.selectTargetAllots.map(item =>item.id);
            if (!checklist.length) {
                this.$Message.warning('请选择任务')
                return
            }
            batchModificationStatus(checklist, status).then(({ code, message }) => {
                if (code === 1) {
                    if (status === 1) {
                        this.$Message.info('批量展示成功')
                    } else {
                        this.$Message.info('批量隐藏成功')
                    }
                    this.queryTargetAllot();
                    this.selectTargetAllots = [];
                } else {
                    this.$Message.warning(message)
                }
            })
        },
    	getProjectInfo(){
			getstatusbyprjid(this.$route.query.prjid).then(data => {
				if(data.code == 1){
					this.projectInfo = data.attribute;
					this.getProjectSubnet();
				}
			})
		},
		getTargetTeamList(){
	  		getTargetTeamList_new(this.queryTargetTeamInfo).then(data => {
	  			if(data.code==1){
	  				this.targetTeamData = data.data.items || data.data;
	  				this.targetTeamData.forEach(team => {
						this.idwithName[team.id] = team;
					})
	  				this.targetTeamTotal = data.data.total;
	  			}else{

	  			}
	  		})
	  	},
    	initData(){
    		this.formValidate = {
			  "idsTOS": [],
			  "targetId": "",
			  "teamIds":[],
			  "visibility": 0,
			}
    	},
    	getAllVmlist(){
    		let _this = this;
    		let target = this.targetTeamData.filter(target => target.id == targetId)[0];
    		
	        let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc',
				findPorts:true,
			}
			queryVmWithParty(this.routeParams.prjid,params).then(data => {
				if(data.code == 1){
					this.vmlists = data.data.list || data.data;
					this.vmlists.forEach(vm => {
						this.idwithName[vm.id] = {
							id:vm.id,
							name:vm.name
						}
					})
				}
			})
	    },
	    getPhyDevNodeList(){
	    	let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc',
				projectId:this.$route.query.prjid,
				findPorts:true,
			}
	    	getPhyDevNodeList(params).then(data => {
	    		if(data.code == 1){
					this.allPhyDevices  = data.data.list;
					this.allPhyDevices.forEach(vm => {
						this.idwithName[vm.id] = {
							id:vm.id,
							name:vm.name
						}
					})
				}else{
					
				}
	    	})
	    },
        getAccessGroupList(){
			if(!this.routeParams.id){
				return;
			}
			let params = {
				pageIndex:1,
				pageSize:2147483647,
				testId:this.routeParams.id
			};
			this.selectGroupList = [];
			getaccessgrouplist(params).then(data => {
				if(data.code == 1){
					this.accessGroupList = data.data.items;
					this.accessGroupList.forEach(group => {
						this.idwithName[group.id] = {
							id:group.id,
							name:group.name
						}
					})
				}else if(data.code == -2) {
					this.accessGroupList = [];
				}else{
					this.$Message.warning(data.message);
				}
			})
		},
		showAddAndUpdate(info){
    		this.initData();
    		this.$refs ['formValidate'].fields.forEach(function (e) {
			     if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
    		this.targetModal.show = true;
    		if(!info){
    			this.targetModal.title = '任务分配';
    			this.targetModal.type = 1;
    			this.access = "1";
    		}else{

    		}
    	},
    	handleReset (name) {
//	        this.$refs[name].resetFields();
	        this.addTarget = false;
	        this.initData();
	        this.$refs [name].fields.forEach(function (e) {
			     if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
	    },
	    getTargetSize(size){
	        this.queryTargetAllotInfo.pageSize = size;
	        this.queryTargetAllot();
	    },
	    getTargetPage(page){
	        this.queryTargetAllotInfo.pageIndex = page;
	        this.queryTargetAllot();
	    },
	    changeTeamGroup(){
            this.$nextTick(() => {
                if (!this.isMultiple && this.formValidate.teamIds.length > 1) {
                    this.$Message.warning('Checker任务只允许分配给一个团队')
                    this.formValidate.teamIds = this.formValidate.teamIds.slice(0, 1)
                }
            })
	    },
	    changeTarget(targetId){
			this.formValidate.teamIds = []
			this.currentTargetId = targetId
	    	if(this.targetModal.show && targetId){
	    		this.queryTargetAllotRelation();
	    	}
            // 如果是check任务，只允许分配各一个队伍
            let template = this.targetTeamData.find(item => item.id === this.formValidate.targetId)
            if (template && template.isNeedSubmitFlag === '2') { // 单选
                this.isMultiple = false
            } else { // 多选
                this.isMultiple = true
            }
	    	if(this.modifyTargetModal.show){
	    		this.allotFormValidate.vmId = '';
	    		this.allotFormValidate.vmName = '';
	    	}
	    },
	    getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			let linkList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    				if(item.links){
	    					linkList = linkList.concat(item.links);
	    				}
	    			})
	    			this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
	    			this.subnetList.forEach(subnet => {
	    				let ip;
	    				if(this.type == 1){
	    					if(linkList.filter(link => link.rightNetId == subnet.id).length > 0){
	    						ip = linkList.filter(link => link.rightNetId == subnet.id)[0].rightIpParts[0].ipAddress; //新接口这个字段没有了
	    					}
	    				}
						this.idwithName[subnet.id] = {
							id:subnet.id,
							name:subnet.name,
							ip:ip
						}
					})
	    		}
	    	})
	    },
	    addIdTOS(){
			this.formValidate.teamIds.forEach(teamId => {
				let target = this.idwithName[this.formValidate.targetId];
				let obj = this.idwithName[target.questionId] || this.idwithName[target.id]
				this.formValidate.idsTOS.push({
		    		"vmId":obj.id,
					"vmName":obj.name,
					"teamId":this.idwithName[teamId].id,
		      		"teamName":this.idwithName[teamId].name,
		      		"subnetId":this.formValidate.subnetId,
				    "subnetName":this.formValidate.subnetId ? this.idwithName[this.formValidate.subnetId].name : '',
					"externalIp":this.formValidate.externalIp, //对外ip
					"externalPort": this.formValidate.externalPort, //对外端口
					"externalServicePort":this.formValidate.externalServicePort,
					"visibility": this.formValidate.visibility
		    	})
			})
	   },
	   targetAllot(){
	    	this.$refs['formValidate'].validate((valid) => {
	    		this.addIdTOS();
	            if (valid) {
			   	    let params = {
					  "idsTOS": this.formValidate.idsTOS,
					  "targetId": this.formValidate.targetId
					}
			   	    targetAllot(params).then(data => {
			   	    	if(data.code == 1){
			   	    		this.queryTargetAllot();
			   	    		this.targetModal.show = false;
			   	    		this.formValidate.vmId = '';
			   	    		this.formValidate.teamId = '';
			   	    		if (this.stMode == 0) {
                                this.formValidate.visibility = 1
                            } else {
                                this.formValidate.visibility = 0;
                            }
			   	    	}else{
			   	    		this.cancelLoading('targetModal');
			   	    	}
			   	    }).catch(error => {
			   	    	this.cancelLoading('targetModal');
			   	    })
			    }else{
			    	this.cancelLoading('targetModal');
			    }
	   		})
	   },
	   autoAllotTopoTarget(){
	   	  autoAllotTopoTarget(this.$route.query.id).then(data => {
	   	  	if(data.code == 1){
	   	  		 this.$Message.info('操作成功');
                // 分配成功后清空搜索条件，回退到首页
                this.queryTargetAllotInfo.pageIndex = 1
                this.queryTargetAllotInfo.visibility = ''
                this.queryTargetAllotInfo.targetName = ''
                this.queryTargetAllotInfo.teamName = ''
                this.selectAll = false
	   	  		 this.queryTargetAllot();
	   	  	}else{
	   	  		this.$Message.warning(data.message);
	   	  	}
	   	  }).catch(() => {
	   	  })
	   },
	   //queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot
	   queryTargetAllot(){
            if (this.queryTargetAllotInfo.teamName) { // 按团队名搜索，需要排序
                this.queryTargetAllotInfo.sortBy = 'sequence'
            } else { // 不需要排序
                delete this.queryTargetAllotInfo.sortBy
            }
	   		queryTargetAllot(this.queryTargetAllotInfo).then(data => {
	   			if(data.code == 1){
            let lists = data.data.items
            for(let i=0;i<lists.length;i++){
              lists[i].name = lists[i].targetName
            }

            this.targetAllotList = lists;
            
	   				this.targetAllotTotal = data.data.total;
	   				if(this.step == 'pre'){
		   				if(this.targetAllotTotal > 0){
		   					this.$emit('setHasTarget',true);
		   				}else{
		   					this.$emit('setHasTarget',false);
		   				}
	   				}
	   			}else{
	   				this.$Message.warning(data.message);
	   				if(this.step == 'pre'){
	   					this.$emit('setHasTarget',false);
	   				}
	   			}
	   		}).catch(error => {
	   			if(this.step == 'pre'){
	   				this.$emit('setHasTarget',false);
	   			}
	   		})
	   },
	   queryTargetAllotRelation(){
	   	   let params = {
	   	   	   pageIndex:1,
	   	   	   pageSize:1000,
//	   	   	   subnetId:this.formValidate.subnetId,
	   	   	   basicTargetId:this.formValidate.targetId,
	   	   	   sceneId:this.$route.query.id
	   	   }
	   		queryTargetAllotRelation(params).then(data => {
	   			if(data.code == 1){
	   				this.formValidate.teamIds = data.data.items.map(item => item.teamId);
	   			}else{
	   			this.$Message.warning(data.message);
	   		  }
	   	    }).catch(error => {
	   		})
	   },
	   modifyTargetAllot(){
	   	    this.$refs['allotFormValidate'].validate((valid) => {
	            if (valid) {
			   	   let params = {
			   	   	  "createTime":this.allotFormValidate.createTime,
					  "externalIp": this.allotFormValidate.externalIp,
					  "externalPort": this.allotFormValidate.externalPort,
					  "externalServicePort":this.allotFormValidate.externalServicePort,
					  "id": this.allotFormValidate.id,
					  "sceneId": this.allotFormValidate.sceneId,
					  "subnetId": this.allotFormValidate.subnetId,
					  "subnetName": this.idwithName[this.allotFormValidate.subnetId].name,
					  "basicTargetId": this.allotFormValidate.basicTargetId,
					  "targetName": this.idwithName[this.allotFormValidate.basicTargetId].name,
					  "teamId": this.allotFormValidate.teamId,
					  "teamName": this.idwithName[this.allotFormValidate.teamId].name,
					  "visibility": this.allotFormValidate.visibility,
					  "vmId": this.allotFormValidate.vmId,
					  "vmName": this.idwithName[this.allotFormValidate.vmId].name,
			   	   }
			   	   modifyTargetAllot(params.id,params).then(data => {
			   	   	  if(data.code == 1){
			   	   	  	this.queryTargetAllot();
			   	   	  	this.modifyTargetModal.show = false;
			   	   	  	this.cancelLoading('modifyTargetModal');
			   	   	  	this.$Message.info('操作成功');
			   	   	  }else{
			   			this.$Message.warning(data.message);
			   		  }
			   	    }).catch(error => {
			   			this.cancelLoading('modifyTargetModal');
			   		})
			   	}else{
			   		this.cancelLoading('modifyTargetModal');
			   	}
	        })
	   },
	   cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    closeTargetModal(){
	    	this.handleReset('formValidate');
//	    	this.handleReset('addFormValidate');
	    }
    }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
 .not-close /deep/ .ivu-tag-checked .ivu-tag-text {
	margin-right: 0;
 }
 .not-close /deep/ .ivu-tag-checked .ivu-icon-ios-close {
	display: none;
 }
  .targetHeader{
    /*padding: 10px;*/
    margin:15px 0;
  }
</style>
